import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

import '../../../common/utils/index.dart';
import '../../../common/values/index.dart';
import '../../../common/widgets/index.dart';
import 'index.dart';

class PortalPage extends GetView<PortalController> {
  @override
  final String? tag;

  const PortalPage({Key? key, required this.tag}) : super(key: key);

  static void open(String portalId, {String title = '', String? pageId}) async {
    Get.lazyPut<PortalController>(() => PortalController(), tag: portalId);
    await Get.to(PortalPage(tag: portalId),
        arguments: {"portalId": portalId, "title": title, "pageId": pageId}, preventDuplicates: false);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<PortalController>(
      tag: tag,
      builder: (_) {
        return Obx(() => Scaffold(
          appBar: controller.state.hiddenAppBar ? null
          : AppBar(
              automaticallyImplyLeading: false,
              title:  Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    IconButton(
                      icon: const Icon(Icons.arrow_back),
                      onPressed: () => {controller.tapBackBtn()},
                    ),
                    IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () => {controller.tapCloseBtn()},
                    ),
                    Expanded(flex: 1, child: Text(controller.state.title))
                  ],
                ),
              actions: [O2UI.webviewPopupMenu(() => controller.copyLink())]),
          body: SafeArea(
            child: controller.state.url.isEmpty
                ? const Center(child: CircularProgressIndicator())
                : _buildView()),
          ),
        );
      },
    );
  }

  // 主视图
  Widget _buildView() {
    return InAppWebView(
        key: controller.webViewKey,
        initialUrlRequest: URLRequest(url: Uri.parse(controller.state.url)),
        initialOptions: InAppWebViewGroupOptions(
            crossPlatform: InAppWebViewOptions(
              useShouldOverrideUrlLoading: true,
              useOnDownloadStart: true,
              javaScriptCanOpenWindowsAutomatically: true,
              mediaPlaybackRequiresUserGesture: false,
              applicationNameForUserAgent: O2.webviewUserAgent
            ),
            android: AndroidInAppWebViewOptions(
              useHybridComposition: true,
              supportMultipleWindows: true,
            ),
            ios: IOSInAppWebViewOptions(
              allowsInlineMediaPlayback: true,
            )),
        androidOnGeolocationPermissionsShowPrompt:(controller, origin) async {
          return GeolocationPermissionShowPromptResponse(
            origin: origin,
            allow: true,
            retain: true
          );
        },
        onWebViewCreated: (c) {
          controller.setupWebviewJsHandler(c);
        },
        // onCreateWindow: (c, createWindowRequest) async {
        //   OLogger.d("创建新窗口，，，，${createWindowRequest.request.url}");
        // },
        shouldOverrideUrlLoading: (c, navigationAction) async {
          var uri = navigationAction.request.url!;
          OLogger.d("shouldOverrideUrlLoading uri: $uri");
          // c.loadUrl(urlRequest: URLRequest(url: uri));
          return NavigationActionPolicy.ALLOW;
        },
        onProgressChanged: (c, p) {
         controller.progressChanged(c, p);
        },
        // h5下载文件
        onDownloadStartRequest: (c, request) async {
          controller.webviewHelper.onFileDownloadStart(request);
        },
        onTitleChanged: ((c, title) {
          OLogger.d('修改网页标题： $title');
          if (title != null && title.isNotEmpty) {
            controller.state.title = title;
          }
        }),
        onConsoleMessage: (c, consoleMessage) {
          OLogger.i("console: $consoleMessage");
        });
  }
}
